package com.hzt.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzt.system.common.ActiveUser;
import com.hzt.system.common.Constant;
import com.hzt.system.common.MenuTreeNode;
import com.hzt.system.common.ResultObj;


import com.hzt.system.domain.Loginfo;
import com.hzt.system.domain.Menu;
import com.hzt.system.domain.User;
import com.hzt.system.service.LoginfoService;
import com.hzt.system.service.MenuService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import jdk.nashorn.internal.runtime.JSONFunctions;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
*
*
* @Author:hzt
* @Date:12:58 上午 2020/7/7
*/
@Controller
@RequestMapping("api/login")
public class LoginController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private LoginfoService loginfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户登录
     */
    @RequestMapping("doLogin")
    @ResponseBody
//    @CrossOrigin
    public ResultObj doLogin(String loginname, String password,String captcha,String keycode, HttpServletRequest request){

        try {
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String code = opsForValue.get(keycode);
            if(code==null){
                return new ResultObj(-1,"验证码已过期");
            }else {
                if(code.equalsIgnoreCase(captcha)){
                    Subject subject= SecurityUtils.getSubject();
                    UsernamePasswordToken loginToken = new UsernamePasswordToken(loginname, password);
                    subject.login(loginToken);
//            ActiveUser activeUser=(ActiveUser) subject.getPrincipal();
                    //得到hhiro的SessionId,就是token
                    String token = subject.getSession().getId().toString();

                    //写入登录日志
                    ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
                    String  name = activeUser.getUser().getName()+"-"+activeUser.getUser().getLoginname();
                    Loginfo loginfo=new Loginfo();
                    loginfo.setLoginname(name);
                    loginfo.setLoginip(request.getRemoteAddr());
                    loginfo.setLogintime(new Date());
                    loginfoService.save(loginfo);
                    List<String> permissions = activeUser.getPermissions();
                    Map<String,Object> map=new HashMap<>();
                    map.put("permissions", permissions); //用于登录按钮权限
                    map.put("token", token);     //用于登录认证
                    map.put("userType",activeUser.getUser().getType());  //解决管理员权限丢失问题
                    map.put("userName", activeUser.getUser().getName()); //解决用户登录名显示
                    return new ResultObj(200,"登录成功",map);
                }else {
                    return new ResultObj(-1,"验证码不正确");
                }
            }
        }catch (AuthenticationException e){
            e.printStackTrace();
            return new ResultObj(-1,"用户名或密码不正确");

        }
    }

    /**
     * 返回验证码
     */


    /**
     * 获取菜单
     */
    @RequestMapping("loadIndexMenu")
    @ResponseBody
//    @CrossOrigin
    public Object loadIndexMenu(){
        //得到当前登录的用户
        Subject  subject= SecurityUtils.getSubject();
        ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
         User user = activeUser.getUser();
        if(user==null){
            return null;
        }
        List<Menu> menus=null;
        if(user.getType().equals(Constant.USER_TYPE_SUPER)){//超级管理员
            menus=menuService.queryAllMenuForList();
        }else {
            menus=menuService.queryMenuForListByUserId(user.getId());
        }
        List<MenuTreeNode> treeNodes=new ArrayList<>();
        for (Menu m : menus) {
            Boolean spread=m.getSpread()==Constant.SPREAD_TRUE?true:false;
            treeNodes.add(new MenuTreeNode(m.getId(),m.getPid(),m.getTitle(),m.getHref(),m.getIcon(),spread,m.getTarget(),m.getTypecode()));
        }
        List<MenuTreeNode> nodes = MenuTreeNode.MenuTreeNodeBuilder.build(treeNodes, 0);
        Map<String,Object> res=new HashMap<>();
        for (MenuTreeNode n : nodes) {
            res.put(n.getTypecode(),n);
        }
//        String json = JSON.toJSONString(res);
//        return  json.replace("\"child\":[],", "");
        return res;
    }

    /**
     * 验证是否登录
     * @return
     */
    @RequestMapping("checkLogin")
    @ResponseBody
//    @CrossOrigin
    public ResultObj checkLogin(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            System.out.println(ResultObj.IS_LOGIN);
            return ResultObj.IS_LOGIN;
        }else {
            return ResultObj.UN_LOGIN;
        }
    }


    @RequestMapping("captcha")
    public void captcha(HttpServletResponse response,String codekey) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 38, 4, 4);
        String code=captcha.getCode();
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(codekey, code);
        opsForValue.getOperations().expire(codekey, 60, TimeUnit.SECONDS);
        captcha.write(response.getOutputStream());
    }
}
